package com.example.demofdfs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

//@ControllerAdvice
public class MyExceptionHandler {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public List<Map<String, String>> MethodArgumentNotValidException(Exception ex, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
//		logger.warn(":" + request, ex);
		MethodArgumentNotValidException c = (MethodArgumentNotValidException) ex;
		List<ObjectError> errors = c.getBindingResult().getAllErrors();
		StringBuffer errorMsg = new StringBuffer();
		errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
//		pouplateExceptionResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, errorMsg.toString());
		List<Map<String, String>> list = new ArrayList<>();
		
		for (ObjectError error : errors) {
			FieldError e = (FieldError) error;
			Map<String, String> map = new HashMap<>();
			map.put(e.getField(), error.getDefaultMessage());
			list.add(map);
		}
		return list;
	}

	@ExceptionHandler(RuntimeException.class)
	@ResponseBody
	public void test(Exception ex, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.getOutputStream().write(ex.getMessage().getBytes());
	}
}
